<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="用户编号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      style="width: 100%; margin-top:10px;"
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="150" prop="id">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="用户编号" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.userId }}
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.telephone }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row.userId)">
            修改
          </el-button>
          <el-button v-if="scope.row.id != 1" size="mini" type="danger" @click="handleDelete(scope.row.userId)">
            删除
          </el-button>
          <el-button size="mini" type="info" @click="handleDelete(scope.row.id)">
            重置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <!-- 添加或修改的页面  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="formRules" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px;">
        <!-- 隐藏id -->
        <el-input v-if="false" v-model="temp.id" />
        <el-form-item label="用户编号" prop="userId" label-width="100px">
          <el-input v-model="temp.userId" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="username" label-width="100px">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item v-if="dialogStatus!='update'" label="密码" prop="password" label-width="100px">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone" label-width="100px">
          <el-input v-model="temp.telephone" />
        </el-form-item>
        <el-form-item label="用户角色" label-width="100px">
          <el-checkbox-group v-model="checkList">
            <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId" @change="handleChecked">
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, getUser, addUser, updateUser, deleteUser } from '@/api/user'
import { getRoleList } from '@/api/role'
import Pagination from '@/components/Pagination'
import Vue from 'vue'

export default {
  components: { Pagination },
  data() {
    const validateUserId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('用户编号不能为空'))
      } else {
        callback()
      }
    }
    const validateUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('用户姓名不能为空'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (this.dialogStatus === 'create' && value === '') {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const validateTelephone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else {
        callback()
      }
    }
    return {
      formRules: {
        userId: [{ required: true, trigger: 'blur', validator: validateUserId }],
        username: [{ required: true, trigger: 'blur', validator: validateUserName }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        telephone: [{ required: true, trigger: 'blur', validator: validateTelephone }]
      },
      // 查询发送数据
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        title: undefined
      },
      // 用户列表
      list: null,
      // 角色列表
      roleList: null,
      // 用户数据总数
      total: 0,
      listLoading: true,
      // 查询到的用户角色
      userRoles: [
        { id: '',
          userId: '',
          roleId: ''
        }
      ],
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      temp: {
        id: undefined,
        userId: '',
        username: '',
        password: '',
        telephone: '',
        status: 0
      },
      // 选中的用户角色
      checkList: []
    }
  },
  created() {
    this.fetchData()
    // 获取所有角色
    getRoleList(this.listQuery).then(response => {
      this.roleList = response.data.content
    })
  },
  methods: {
    handleFilter() {
      this.listQuery.pageNum = 1
      if (this.listQuery.title.length === 0) {
        this.listQuery.title = undefined
      }
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.content
        this.total = response.data.totalSize
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userId: '',
        username: '',
        password: '',
        telephone: '',
        status: '',
        checkList: []
      }
    },
    handleCreate() {
      this.resetTemp()
      // 清空选中角色列表
      this.checkList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          Vue.set(tempData, 'checkList', this.checkList)
          addUser(tempData).then(() => {
            this.list.push(tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      // 清空选中角色列表
      this.checkList = []
      // 获取用户信息
      getUser(row).then(response => {
        this.temp = Object.assign({}, response.data)
        this.userRoles = response.data.roles
        this.userRoles.forEach((item, index, arr) => {
          this.checkList.push(item.roleId)
        })
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          Vue.set(tempData, 'checkList', this.checkList)
          updateUser(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(id) {
      this.dialogdeleteVisible = true
      this.temp.id = id
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(this.temp.id).then(() => {
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleChecked() {
    }
  }
}
</script>
